package com.baizhi.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义网关全局Filter
 */
@Configuration
public class CustomerGlobalFilter implements GlobalFilter, Ordered {

    /**
     * 类似JavaWeb filterChain方法
     * exchange 封装了 request response
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        System.out.println("经过全局Filter处理...");
        // 放行Filter继续向后处理
        Mono<Void> filter = chain.filter(exchange);
        System.out.println("响应回来Filter处理...");
        return filter;
    }

    /**
     * 用来指定Filter执行顺序，默认顺序按照自然数字进行排序
     * -1：在所有Filter执行之前执行
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
